package model;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import data.Game;
import data.Player;
import data.Score;


@Path("/score")
public class ScoreService {
	
	public final static String PATH = "../data/DATA_score";
	public final static String PATH_TMP = "../data/DATA_score_tmp";
	
	@GET()
	@Path("/{id_player}")
	@Produces({MediaType.APPLICATION_XML})
	public LinkedList<Score> getScores(@PathParam("id_player") Integer id_player) {
		String line = "";
		LinkedList<Score> scores = new LinkedList<Score>();
		Player p = PlayerService.getById(id_player);
		
		try {
			BufferedReader file = new BufferedReader(new FileReader(ScoreService.PATH));
			while ((line = file.readLine()) != null) {
				String[] l = line.split(",");
				if (Integer.parseInt(l[0]) == id_player) {
					Game g = GameService.getById(Integer.parseInt(l[1]));
					Score s = new Score(p, g, Integer.parseInt(l[2]), Boolean.valueOf(l[3]));
					scores.add(s);
				}
			}
			file.close();
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return scores;
	}
	
	@GET
	@Path("/add/{idplayer}/{idgame}/{points}")
	@Produces({MediaType.APPLICATION_XML})
	public Score save(
			@PathParam("idplayer") Integer idplayer,
			@PathParam("idgame") Integer idgame,
			@PathParam("points") Integer points) {
		Score s = new Score();
		try {
			PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(ScoreService.PATH, true)));
			Game g = GameService.getById(idgame);
			Player p = PlayerService.getById(idplayer);
			s.setGame(g).setPlayer(p).setPoints(points);
			out.println(s.getPlayer().getId()+","+s.getGame().getId()+","+s.getPoints()+",0");
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return s;
	}
	
}
